import {messages} from 'share/common';
import React from 'react';

import { Input, message, Form, Button, Row, Col, Radio, Checkbox, Icon, notification } from 'antd';
import 'styles/financial-management/scan-send-wrap.scss';
import menuRoute from 'routes/menuRoute';
import {connect} from 'react-redux';
import errorMessage from 'share/errorMessage';
import openSlideFrame from 'share/openSlideFrame';
import SlideExpenseReportDetail from 'containers/financial-management/new-finance-audit/slide-expense-report-detail';
import QuickReply from 'components/template/quick-reply';
import Condition from 'components/condition'
import routeService from 'routes/route.service';
import ScanReceiveService from 'containers/scan-receive/scan-receive.service'
import financeAuditService from 'containers/financial-management/new-finance-audit/finance-audit.service';
import WaterMark from 'components/water-mark';

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const { TextArea } = Input;

const { If } = Condition;

class ScanGunAudit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      financeAudit: menuRoute.getRouteItem('finance-audit'),
      OperaParamsMap: {
        DETAIL: {
          operate: 'WEB_REVIEW_JUMP',
          successNotice: messages('common.operate.success')/*操作成功*/,
          errorNotice: messages('common.operate.filed')/*操作失败*/
        },
        AUDIT_PASS: {
          operate: 'WEB_AUDIT_PASS',
          successNotice: messages('expense-14.key258')/*审核成功*/,
          errorNotice: messages('expense-14.key259')/*审核失败*/
        },
        REJECT: {
          operate: 'WEB_AUDIT_REJECT',
          successNotice: messages('expense-14.key258')/*审核成功*/,
          errorNotice: messages('expense-14.key259')/*审核失败*/
        },
        RECEIVE: {
          successNotice: messages('expense-14.key260')/*收单成功*/,
          errorNotice: messages('expense-14.key261')/*收单失败*/
        },
      },
      operaOptions: [{
        value: 'DETAIL',
        label: messages('expense-14.key262')/*进入单据详情页*/
      }, {
        value: 'AUDIT_PASS',
        label: messages('expense-14.key27')/*审核通过*/
      }, {
        value: 'REJECT',
        label: messages('expense-14.key57')/*审核驳回*/
      }],
      receiveBillOptions: [{
        value: 'true',
        label: messages('common.yes')/*是*/
      }, {
        value: 'false',
        label: messages('common.no')/*否*/
      }],
      inputError: false,
      errorMessage: '',
      attachmentOIDs: [],
      addRemarkStatus: false,
      formInfo: '',
      scanResult: {},
      isRejecting: false,
      identifying: false,
      inputValue: '',
      openNewPage: false,
      operaStatus: localStorage.getItem("scan-gun-audit-opera-status") || "DETAIL", // 操作状态
      detailMode: localStorage.getItem("scan-gun-audit-to-detail-mode"), //进入单据详情页模式
      receiveBill: localStorage.getItem("scan-gun-audit-receive-bill") || "false", //收单操作
      asyncAudit: localStorage.getItem("scan-gun-audit-async-audit") //收单操作
    };
  }

  componentDidMount() {
    this.focusInput();
    notification.config({
      getContainer: () => document.getElementsByClassName('scan-gun-audit-notice-container')[0]
    })
  }

  componentWillUnmount() {
    notification.config({
      getContainer: () => document.body
    });
    notification.destroy();
  }

  //收单操作
  handleReceiveBills = value => {
    this.setState({ identifying: true, addRemarkStatus: false });
    ScanReceiveService.receive(value).then(res => {
      //entityType: 报销单(1002),借款单(3001),发票袋(5001)
      let formInfo = res.data.entityType === 5001 ? messages('expense-14.key248')/*发票袋*/ :
        messages('expense-14.key247')/*单据*/;
      formInfo = res.data.businessCode ? `${formInfo} ${res.data.businessCode}` : '';
      this.renderNotification(res.data.success, 'RECEIVE', `${formInfo} ${res.data.msg}`);
      this.handleOperateBills(value);
    }).catch(err => {
      this.setState({ identifying: false, inputValue: '' });
      this.props.form.resetFields();
      errorMessage(err.response);
    })
  };

  //扫码后操作
  handleOperateBills = value => {
    let { operaStatus, OperaParamsMap, detailMode, asyncAudit } = this.state;
    let params = {
      code: value,
      resourceId: routeService.getResourceIdByMenu(),
      operate: OperaParamsMap[operaStatus].operate,
      autoIdentify: true,
      asyncAudit
    };
    this.setState({ identifying: true, addRemarkStatus: false });
    financeAuditService.scan(params).then(res => {
      //entityType: 报销单(1002),借款单(3001),发票袋(5001)
      let entityType = res.data.entityType;
      let formInfo = entityType === 5001 ? messages('expense-14.key248')/*发票袋*/ :
        messages('expense-14.key247')/*单据*/;
      formInfo = res.data.businessCode ? `${formInfo} ${res.data.businessCode}` : '';
      if (res.data.success) {
        if (operaStatus === 'DETAIL') { // 进入详情页处理
          this.props.form.setFieldsValue({ reason: '' });
          this.setState({ inputValue: '', openNewPage: true });
          //对公支付单
          if(res.data.corporateFlag) {
            this.input.blur();
            openSlideFrame.openCorporateReportDetail({
              expenseReportOID: res.data.entityOid,
              entry: 'audit'
            }, {
              noPadding: true,
              className: 'corporate-payment-report-detail',
              afterClose: () => {
                this.focusInput();
                this.setState({ openNewPage: false });
              },
            }, this);
            return;
          }
          // 单据为报销单 或者发票袋
          if (~[1002, 5001].indexOf(entityType)) {
            openSlideFrame.openExpenseReport({
              expenseReportOID: res.data.entityOid,
              status: 'prending_audit',
              entry: 'audit',
              backType: 'history',
              activeTab: detailMode || 'expense',
              applicantOID: res.data.applicantOID
            }, {
              afterClose: () => {
                this.focusInput();
                this.setState({ openNewPage: false });
              },
              content: SlideExpenseReportDetail,
              noPadding: true,
            }, this);
          } else {
            openSlideFrame.openLoanReport({
              formOID: res.data.formOid,
              loanBillOID: res.data.entityOid,
              backType: 'history',
              status: 'prending_audit',
              pathname: this.props.location.pathname,
              entry: 'audit',
            }, {
              afterClose: () => {
                this.focusInput();
                this.setState({ openNewPage: false });
              },
            }, this);
          }
        } else if (operaStatus === 'AUDIT_PASS') { // 审核通过
          this.renderNotification(true, operaStatus, `${formInfo} ${res.data.msg}`);
          this.props.form.setFieldsValue({ reason: ''});
          this.setState({inputValue: ''});
          this.focusInput();
        } else { // 审核驳回
          this.setState({
            addRemarkStatus: true,
            formInfo,
            scanResult: res.data,
            attachmentOIDs: []
          });
          this.props.form.setFieldsValue({ reason: '' });
        }
      } else {
        this.renderNotification(false, operaStatus, `${formInfo} ${res.data.msg}`);
        this.props.form.setFieldsValue({ reason: '' });
        this.setState({inputValue: ''});
        this.focusInput();
      }
    }).catch(err => {
      this.props.form.setFieldsValue({ reason: ''});
      this.setState({inputValue: ''});
      errorMessage(err.response);
      this.focusInput();
    }).finally(() => {
      this.setState({ identifying: false });
    });
  };

  renderNotification = (success, operate, description) => {
    const { OperaParamsMap } = this.state;
    notification[success ? 'success' : 'error']({
      message: OperaParamsMap[operate][success ? 'successNotice' : 'errorNotice'],
      description,
      duration: success ? 3 : null
    });
    let noticeContainer = document.getElementsByClassName('scan-gun-audit-notice-container')[0];
    let _scrollHeight = noticeContainer.scrollHeight;
    let _offsetHeight = noticeContainer.offsetHeight;
    noticeContainer.scrollTop = _scrollHeight > _offsetHeight ? _scrollHeight - _offsetHeight : 0
  };

  handlePressEnter = e => {
    const { operaStatus, receiveBill } = this.state;
    if (operaStatus !== 'REJECT' && receiveBill === 'true') {
      this.handleReceiveBills(e.target.value);
    } else {
      this.handleOperateBills(e.target.value);
    }
  };

  focusInput = () => {
    setTimeout(() => {
      this.input.focus();
    }, 300);
  };

  handleClickSwitch = () => {
    this.context.router.push(this.state.financeAudit.url);
  };

  //审批意见输入
  onReasonChange = () => {
    let rejectReason = this.props.form.getFieldsValue().reason;
    this.setState({
      inputError: rejectReason.length > 500,
      errorMessage: messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/
    });
  };

  handleImageUpload = attachments => {
    this.setState({attachmentOIDs: attachments.map(a => a.attachmentOID)});
  };

  rejectHandle = () => {
    let { scanResult, attachmentOIDs } = this.state;
    const {getFieldsValue} = this.props.form;
    let rejectReason = getFieldsValue().reason;
    if (!rejectReason) {
      this.setState({
        inputError: true,
        errorMessage: messages('expense-14.key252')/*请输入驳回意见*/
      });
      message.error(messages('expense-14.key252')/*请输入驳回意见*/);
      return !1;
    }
    if (rejectReason.length > 500) {
      this.setState({
        inputError: true,
        errorMessage: messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/
      });
      message.error(messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/);
      return !1;
    }
    let params = {
      approvalTxt: rejectReason,
      entities: [{
        entityOID: scanResult.entityCode,
        entityType: scanResult.entityType,
        attachmentOIDs
      }]
    };
    this.setState({isRejecting: true});
    financeAuditService.rejectAudit(params)
      .then(res => {
        let formInfo = res.data.entityType === 5001 ? messages('expense-14.key248')/*发票袋*/ :
          messages('expense-14.key247')/*单据*/;
        formInfo = res.data.entityCode ? `${formInfo} ${res.data.entityCode}` : '';
        this.setState({isRejecting: false});
        this.renderNotification(res.data.success, 'REJECT', `${formInfo} ${res.data.msg}`);
        if (res.data.success) {
          this.cancelHandle();
        }
      })
      .catch(err => {
        this.setState({isRejecting: false});
        errorMessage(err.response);
      });
  };

  cancelHandle = () => {
    this.setState({addRemarkStatus: false, attachmentOIDs: []});
    this.props.form.setFieldsValue({reason: ''});
    this.setState({inputValue: ''});
    this.focusInput();
  };

  //修改配置选项
  onOptionsChange = (type, value) => {
    const localStorageMap = {
      operaStatus: 'scan-gun-audit-opera-status',
      detailMode: 'scan-gun-audit-to-detail-mode',
      receiveBill: 'scan-gun-audit-receive-bill',
      asyncAudit: 'scan-gun-audit-async-audit'
    };
    this.setState({ [type]: value });
    localStorage.setItem(localStorageMap[type], value);
  };

  renderRejectArea = () => {
    const {getFieldDecorator} = this.props.form;
    const {inputError, errorMessage, formInfo, isRejecting} = this.state;
    return (
      <div>
        <p style={{
          textAlign: 'left',
          margin: '40px 0 10px',
          fontWeight: '600',
          color: '#1E2126',
          fontSize: '16px'
        }}>
          {formInfo}
        </p>
        <FormItem validateStatus={inputError ? 'error' : ''}
                  help={inputError ? errorMessage : ''}
                  style={{marginBottom: '16px'}}>
          {getFieldDecorator('reason')(
            <QuickReply
              afterChange={this.onReasonChange}
              handleImageUpload={this.handleImageUpload}
              params={{needHonest: false, withAttachments: true, audit: true}}
            >
              <TextArea
                placeholder={messages('expense-14.key253')/*请填写驳回理由*/}
                style={{
                  minHeight: 136,
                  height: 32,
                  resize: 'none',
                  marginBottom: 10,
                  marginLeft: window.ISIE9 ? 20 : 0
                }}
              />
            </QuickReply>
          )}
        </FormItem>

        <Row style={{textAlign: 'left', paddingBottom: '20px'}}>
          <Col span={24}>
            <Button type="danger"
                    loading={isRejecting}
                    onClick={this.rejectHandle}
                    style={{marginRight: '20px'}}>
              {messages('common.reject')/*驳回*/}
            </Button>
            <Button onClick={this.cancelHandle}>
              {messages('common.cancel')/*取消*/}
            </Button>
          </Col>
        </Row>
      </div>
    );
  };

  render() {
    const {
      operaStatus, operaOptions, addRemarkStatus, identifying, detailMode, receiveBillOptions, receiveBill,
      inputValue, asyncAudit, openNewPage
    } = this.state;
    return (
      <div style={{position: 'absolute', minHeight: 'calc(100% - 100px)', width: 'calc(100% - 40px)'}}>
        <WaterMark />
        <div
          className="scan-gun-audit-notice-container"
          style={{ zIndex: openNewPage ? 1 : 'unset' }}
        />
        <div className="scan-send-wrap">
          <div className="scan-send-header">
            <Button type="primary" icon="layout" className="btn-change"
                    onClick={this.handleClickSwitch}>
              {messages('expense-14.key251')/*普通审核*/}
            </Button>
            <h1>{messages('expense-14.key243')/*扫码枪审核*/}</h1>
          </div>
          <Row className="select-options">
            <Col span={5}>
              {messages('expense-14.key263')/*扫码后操作*/}
            </Col>
            <Col span={19}>
              <RadioGroup
                value={operaStatus}
                onChange={e => this.onOptionsChange('operaStatus', e.target.value)}
              >
                {operaOptions.map(option => (
                  <Radio value={option.value} key={option.value}>{option.label}</Radio>
                ))}
              </RadioGroup>
              <If value={operaStatus === 'DETAIL'}>
                <div className="go-to-detail-mode">
                  <Checkbox
                    style={{ marginRight: 8 }}
                    checked={detailMode === 'invoice'}
                    onChange={e => this.onOptionsChange('detailMode', e.target.checked ? 'invoice' : '')}
                  />
                  {messages('expense-14.key513')/*若为报销单或对公支付单，打开单据详情页时，直接进入【发票模式】*/}
                </div>
              </If>
              <If value={operaStatus === 'AUDIT_PASS'}>
                <div className="go-to-detail-mode">
                  <Checkbox style={{ marginRight: 8 }}
                            checked={asyncAudit === 'true'}
                            onChange={e => this.onOptionsChange('asyncAudit', '' + e.target.checked)}
                  /> {messages('expense-14.key265')/*审核通过操作后台处理， 不等待处理结果，可至待审核列表查看审核通过失败单据*/}
                </div>
              </If>
            </Col>
          </Row>
          <If value={~['DETAIL', 'AUDIT_PASS'].indexOf(operaStatus)}>
            <Row className="select-options">
              <Col span={5}>
                {messages('expense-14.key266')/*收单操作*/}
              </Col>
              <Col span={19}>
                <RadioGroup
                  value={receiveBill}
                  onChange={e => this.onOptionsChange('receiveBill', e.target.value)}
                >
                  {receiveBillOptions.map(option => (
                    <Radio value={option.value} key={option.value}>{option.label}</Radio>
                  ))}
                </RadioGroup>
              </Col>
            </Row>
          </If>
          <div style={{position: 'relative'}}>
            <Input
              value={inputValue}
              onChange={e=> this.setState({inputValue: e.target.value})}
              onPressEnter={this.handlePressEnter}
              ref={input => this.input = input}
              className="input-search"
              disabled={identifying}
            />
            <p style={{
              color: '#8B93A7',
              marginTop: '8px'
            }}>{messages('expense-14.key267')/*若您扫码后提示单据不存在，或无法跳转至单据详情页，请尝试：1. 输入法切换至英文环境后再扫码；2. 确认您的扫码枪已设置回车后缀*/}</p>
            <If value={identifying}>
              <Icon type="loading" style={{position: 'absolute', top: '6px', right: '8px', zIndex: 1}}/>
            </If>
          </div>
          {operaStatus === 'REJECT' && addRemarkStatus && (this.renderRejectArea())}
        </div>
      </div>
    );
  }

}

ScanGunAudit.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company
  };
}

const WrappedScanGunAudit = Form.create()(ScanGunAudit);

export default connect(mapStateToProps)(WrappedScanGunAudit);
;
